import 'package:fish_redux/fish_redux.dart' hide PageProvider;
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wowhy/modules/page_provider.dart';
import 'package:wowhy/service_locator.dart';
import 'package:wowhy/services/navigate_service.dart';

import '../../widgets/my_refresh_header.dart';
import '../../widgets/my_refresh_footer.dart';

import 'action.dart';
import 'state.dart';

Widget buildView(
  HomePageState state,
  Dispatch dispatch,
  ViewService viewService,
) {
  return Scaffold(
    appBar: MyAppBar(
      title: Text('首页'),
      centerTitle: true,
      elevation: 0,
    ),
    drawer: buildDrawer(state, dispatch, viewService),
    body: buildBody(state, dispatch, viewService),
  );
}

Widget buildBody(
  HomePageState state,
  Dispatch dispatch,
  ViewService viewService,
) {
  final ListAdapter adapter = viewService.buildAdapter();
  final SmartRefresher listview = SmartRefresher(
    controller: state.refreshController,
    enablePullUp: true,
    enablePullDown: true,
    header: MyRefreshHeader(),
    footer: MyRefreshFooter(),
    onRefresh: () => dispatch(HomePageActionCreator.onRefresh()),
    onLoading: () => dispatch(HomePageActionCreator.onFetch()),
    child: ListView.builder(
      physics: ClampingScrollPhysics(),
      itemBuilder: adapter.itemBuilder,
      itemCount: adapter.itemCount,
    ),
  );

  return Container(
    child: Container(
      child: Column(
        children: <Widget>[
          Expanded(
            child: listview,
          ),
        ],
      ),
    ),
  );
}

Widget buildDrawer(
  HomePageState state,
  Dispatch dispatch,
  ViewService viewService,
) {
  return Drawer(
    child: buildMenu(state, dispatch, viewService),
  );
}

Widget buildMenu(
  HomePageState state,
  Dispatch dispatch,
  ViewService viewService,
) {
  final menus = PageProvider.getMenus();
  return ListView.builder(
    itemBuilder: (context, i) {
      final provider = menus[i];
      return ListTile(
        title: Text(provider.label),
        onTap: () {
          getIt<NavigateService>().pop();
          getIt<NavigateService>().pushNamed(provider.name);
        },
      );
    },
    itemCount: menus.length,
  );
}
